package thesis.filesharing.web.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.google.appengine.api.datastore.KeyFactory;

import thesis.filesharing.bo.StudentBO;
import thesis.filesharing.resources.Constants;
import thesis.filesharing.web.viewmodel.UpdateStudentInfoViewModel;

public class UpdateStudentInfoValidator implements Validator {
	
	@Autowired
	private StudentBO studentBO;
	
	@Override
	public boolean supports(Class<?> clazz) {
		return UpdateStudentInfoViewModel.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "studentName", "studentName.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "studentEmail", "studentEmail.required");
		
		UpdateStudentInfoViewModel model = (UpdateStudentInfoViewModel) target;
		
		if (model.getStudentEmail() != null && model.getStudentEmail().length() > 0) {
			Pattern emailPattern = Pattern.compile(Constants.EMAIL_PATTERN);
			Matcher emailMatcher = emailPattern.matcher(model.getStudentEmail());
			if (!emailMatcher.matches()) {
				errors.rejectValue("studentEmail", "studentEmail.incorrectFormat");
			}
		}
		
		if ("NONE".equalsIgnoreCase(model.getClassName())) {
			errors.rejectValue("className", "className.required");
		}
		
		if ("NONE".equalsIgnoreCase(model.getCourse())) {
			errors.rejectValue("course", "course.required");
		}
		
		if (!errors.hasErrors()) {
			if (studentBO.isEmailDuplicatedWithOrtherStudent(model.getStudentEmail(), KeyFactory.stringToKey(model.getStudentKey()))) {
				errors.reject("studentEmail.exists");
			}
		}
	}
}
